import React, { Component } from 'react'
import _ from 'underscore'
import { Form, Input, Table, Button, Modal, DatePicker, Row, Col } from 'antd';
const FormItem = Form.Item;
import moment from 'moment';
import { ContentHeader } from '../wrapper'
import {message} from "antd/lib/index";
import {connect} from "react-redux";
import {actions} from "../admin/action/action";
import {doAjaxPost} from "./fetch-ajax";

const { RangePicker } = DatePicker;

const dateFormat = 'YYYY/MM/DD';

class QueryTable extends Component {

    onSelectChange (selectedRowKeys) {
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        this.props.onSelectRowChange(selectedRowKeys);
    }
    onSubmit () {
        const rows = this.props.renderdata.goodsList || [];
        const newRows = this.props.selectRows || [];

        const uniquRows = uniqueArr(rows, newRows);
        this.props.onSubmit(uniquRows);
    }
    onDateChange (date, dateString) {
        this.props.searchEntity.startTime = dateString[0];
        this.props.searchEntity.endTime = dateString[1];
    }
    handleSearch (e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            Object.assign( this.props.searchEntity, values);
            this.props.renderData(this.props.searchEntity);
        });
    }
    render() {
        const { dataSource, columns, title, trigerLayer } = this.props;
        const { getFieldDecorator } = this.props.form;

        const rowSelection = {
            onChange: this.onSelectChange.bind(this),
            hideDefaultSelections: true,
            selections: false
            //onSelection: this.onSelection,
        };
        return (
            <Modal title={title} visible={true} onCancel={trigerLayer} width="800px" footer={[
                <Button key="back" size="large" onClick={trigerLayer}  >
                    关闭
                </Button>,
                <Button key="submit" type="primary" size="large" onClick={ this.onSubmit.bind(this) } loading={false}>
                    确认
                </Button>,
            ]} >
                <Form className="ant-advanced-search-form" >
                    <Row gutter={24}>
                        <Col span={7} >
                            <FormItem label="商品名称">
                                {getFieldDecorator(`goodsName`)(
                                    <Input placeholder="商品名称关键字" />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={12} >
                            <FormItem label="上架时间">
                                <RangePicker onChange={this.onDateChange.bind(this)}/>
                            </FormItem>
                        </Col>
                        <Col span={5} >
                            <Button key="submit" type="primary" size="large" onClick={ this.handleSearch.bind(this) } loading={false}>
                                搜索
                            </Button>
                        </Col>
                    </Row>
                    <Row gutter={24}>
                        <Col span={6} >
                            <FormItem label="价格">
                                {getFieldDecorator(`miniPrice`)(
                                    <Input placeholder="最低价" />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={6} >
                            <FormItem label="至">
                                {getFieldDecorator(`maxPrice`)(
                                    <Input placeholder="最高价" />
                                )}
                            </FormItem>
                        </Col><Col span={6} >
                            <FormItem label="折扣">
                                {getFieldDecorator(`miniRate`)(
                                    <Input placeholder="最低折扣" />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={6} >
                            <FormItem label="至">
                                {getFieldDecorator(`maxRate`)(
                                    <Input placeholder="最高折扣" />
                                )}
                            </FormItem>
                        </Col>
                    </Row>

                </Form>

                <Table rowSelection={rowSelection} columns={columns} pagination={{ pageSize: 20 }} dataSource={dataSource} scroll={{ y: 240 }}/>

            </Modal>
        );
    }
}

const QueryTableEx = Form.create({})(QueryTable);

const _QueryTableEx = connect(
    state => {
        return {
            searchEntity: state.goodsSearchEntity,
            renderdata: state.renderdata,
            selectRows: state.selectRows
        }
    },
    dispatch => {
        return {
            onSelectRowChange(rows){
                dispatch({
                    type: 'set-selected-rows',
                    val: rows
                });
            },
            onSubmit(uniquRows){
                fetchGoods(uniquRows).then( (list)=> {
                    for (let g of list) {
                        g.key = g.goodsId;
                    }
                    dispatch({ // 已选中商品merge到goodlist
                        type: 'set-goods-table-data',
                        val: list
                    })
                    dispatch({ // 已选中商品id数组merge到提交数据中
                        type: 'set-renderdata-goodslist',
                        val: uniquRows
                    });
                    dispatch({
                        type: 'trigger-goods-layer'
                    });
                })
            },
            renderData (data){
                doAjaxPost({
                    url: 'https://dingdian-ppe.parllay.cn/wxserver/goods/selectGoodsListBysSalesclerk',
                    data: {
                        data
                    },
                    success: (result)=>{
                        let param = JSON.parse(result);
                        if(param.success){
                            param = param.result.data;
                            for(let g of param){
                                g.key = g.goodsId;
                            }
                            dispatch({
                                type: 'render-goodsDetail-table',
                                val: param
                            });
                        }else{
                            message.error("数据加载失败");
                        }
                    },
                    error: (error)=>{
                        message.error("商品列表加载失败");
                    }
                })
            },
            getGoodsDetail(data) {
                dispatch({
                    type: 'set-goods-table-data',
                    val: data
                })
            },
        }
    }
)(QueryTableEx);

export default _QueryTableEx;

const fetchGoods = function(ids){
    return new Promise(function (resolve, reject) {
        doAjaxPost({
            url: 'https://dingdian-ppe.parllay.cn/wxserver/activity/getGoodsListByIds',
            data: {
                "data": {
                    "storeNo": user.storeNo,
                    "ids": ids
                }
            },
            success: (result) => {
                let param = JSON.parse(result);
                if (param.success) {
                    param = param.result;
                    resolve(param.data);
                } else {
                    reject("数据加载失败");
                }
            },
            error: (error) => {
                reject("数据加载失败");
            }
        })
    })
}

 const uniqueArr = function(arr1, arr2){
    let array = arr1.concat(arr2);
    let r = [];
    for(let i = 0, l = array.length; i < l; i++) {
        for(let j = i + 1; j < l; j++)
            if (array[i] === array[j]) j = ++i;
        r.push(array[i].toString());
    }
    return r;
}